package com.lingnan.blog.controller;

import com.lingnan.blog.entity.User;
import com.lingnan.blog.service.UserService;
import com.lingnan.blog.utils.QiniuUtil;
import com.lingnan.blog.utils.ShiroUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

/**
 * web处理层
 *
 * @author HeGuanChao
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private QiniuUtil qiniuUtil;

    @PostMapping("/register")
    public String register(User user, RedirectAttributes model) {
        try {
            User exitsUser = userService.finByUsername(user.getUsername());
            if (exitsUser != null) {
                model.addFlashAttribute("msg", "用户名已存在");
            } else {
                //插入数据库，把影响的行数写入日志文件
                int row = userService.saveUser(user);
                model.addFlashAttribute("msg", "注册成功");
                //重定向到登录页面
                return "redirect:/login";
            }
        } catch (Exception e) {
            e.printStackTrace();
            model.addFlashAttribute("msg", "服务器开小差了X﹏X");
        }
        //重新返回注册页面
        return "redirect:/register";
    }

    @PostMapping("/login")
    public String login(String username, String password, boolean rememberMe, RedirectAttributes model) {
        Subject userSubject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
        try {
            //登录成功后shiro自动保存用户数据到session
            userSubject.login(token);
            //登录成功跳转到主页
            return "redirect:/index";
        } catch (UnknownAccountException e) {
            model.addFlashAttribute("msg", "未知账号");
        } catch (IncorrectCredentialsException e) {
            model.addFlashAttribute("msg", "用户名或密码错误！");
        } catch (Exception e) {
            model.addFlashAttribute("msg", "服务器开小差了X﹏X");
        }
        //登录失败，重定向登录页面，防止数据保存
        return "redirect:/login";
    }

    @PostMapping("/update")
    public String updateUser(User user, @RequestParam("file") MultipartFile file,
                             RedirectAttributes model, HttpSession session) {
        try {
            if (!file.isEmpty()) {
                //上传头像
                //设置最新的头像路径
                user.setPhoto("http://" + qiniuUtil.upload(file));
            }
            //更新用户数据
            userService.updateUser(user);
            User sessionUser = ShiroUtils.getUser();
            if (StringUtils.isEmpty(user.getPhoto())) {
                //如果用户头像为空，则设置为session的头像
                user.setPhoto(sessionUser.getPhoto());
            }
            //更新session数据
            ShiroUtils.setUser(user);
            //更新成功重定向到”我的资料“页面
            model.addFlashAttribute("msg", "信息更新成功");
            return "redirect:/mydata/" + user.getId();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
